﻿using System;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace OntologyCache
{
    //
    //Wraps up customer marked up text that act as aliases for real tags. Apart from creating a smart tag for the current session we also need to write out the tag to an custom obo file in the correct format
    // also this file never gets cached , we will recreate on each load. Mainly  because number of terms are pretty small so should not be bad to recreare AND the terms probably change a lot so again caching is not 
    // that sensible plus people will add tags all the time which will cause the caches to be recreated a lot
    //
    public class CustomTags
    {
        public void CreateCustomOBOFile(string Path)
        {
            if (File.Exists(Path))
            {
                return;
            }
            StreamWriter sw = File.CreateText(Path);
            sw.Close();
        }

        public void AddCustomTerm(string Term, OntologyCache.OntologyNode onAlias, string FileName, OntologyInfo CustomOnto, bool CreateFile)
        {
            if (true == CreateFile)
            {
                CreateCustomOBOFile(FileName);
            }
        // Add it to the ontologies list in memory data structure
        // Add it to the file
            CustomOnto.AddTerm(Term, onAlias);
            StreamWriter sw = File.AppendText(FileName);
            sw.Write(CreateOBOTermString(Term, onAlias));
            sw.Flush();
            sw.Close();
        
        }


        private string CreateOBOTermString(string Term, OntologyCache.OntologyNode onAlias)
        {
            StringBuilder sbOBO = new StringBuilder();
            sbOBO.AppendLine(@"[Term]");
            sbOBO.AppendLine(string.Format("id: {0}", onAlias.id));
            sbOBO.AppendLine(string.Format("name: {0}", Term));
            sbOBO.AppendLine(string.Format("def: {0}", onAlias.Definition));
            sbOBO.AppendLine(string.Format("OntName: {0}", onAlias.OntologyName));
            sbOBO.AppendLine(string.Format("AliasName: {0}", onAlias.Name));
            sbOBO.Append("\n");

            return sbOBO.ToString();

        }

    }
}